# main.py
from fastapi import FastAPI, Depends, HTTPException, Request, WebSocket
from fastapi.responses import JSONResponse
import uvicorn
from api.router import common, users, ai, ws
from api.src.cache.redis_client import lifespan
from config import appSettings
import os
import sys
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
import pytz

# 设置全局时区为"Asia/Shanghai"
pytz.timezone("Asia/Shanghai")

sys.path.append(os.path.join(os.path.dirname(__file__)))  # 防止相对路径导入出错
app = FastAPI(lifespan=lifespan)
app.include_router(users.router)
# app.add_middleware(AuthMiddleware)
app.include_router(ai.router)
app.include_router(ws.router)
app.include_router(common.router)


# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],
#     allow_credentials=True,
#     allow_methods=["*"],
#     sallow_headers=["*"],
# )
limiter = Limiter(key_func=get_remote_address)

app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.state.limiter = limiter


# app.add_middleware(verify_auth)
@app.exception_handler(HTTPException)
async def unicorn_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"message": exc.detail},
    )


@app.get("/")
async def root():
    return {"message": "hello world"}


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")


if __name__ == "__main__":
    # 打印配置
    print(appSettings)
    uvicorn.run("api_server:app", host="0.0.0.0", port=appSettings.app_port, workers=1)
